import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';
import { Website, WebsiteDocument } from './schemas/website.schema';
import { PageView, PageViewDocument } from './schemas/page-view.schema';

@Injectable()
export class SessionMongoService {
  constructor(
    @InjectModel(Website.name)
    private websiteModel: Model<WebsiteDocument>,
    @InjectModel(PageView.name)
    private pageViewModel: Model<PageViewDocument>,
  ) {}

  async getSessionDetails(sessionId: string): Promise<any> {
    try {
      const visits = await this.pageViewModel
        .find({ sessionId })
        .sort({ createdAt: 1 })
        .populate('websiteId', 'name domain')
        .exec();

      if (visits.length === 0) {
        throw new Error('会话不存在');
      }

      const firstVisit = visits[0];
      const lastVisit = visits[visits.length - 1];
      const duration = lastVisit.createdAt.getTime() - firstVisit.createdAt.getTime();
      const durationInMinutes = Math.round(duration / 60000);
      
      const websiteId = firstVisit.websiteId;
      const website = await this.websiteModel.findById(websiteId);

      const pagesWithDuration = [];
      for (let i = 0; i < visits.length; i++) {
        const visit = visits[i];
        const nextVisit = i < visits.length - 1 ? visits[i + 1] : null;
        let timeOnPage = 0;
        
        if (nextVisit) {
          timeOnPage = (nextVisit.createdAt.getTime() - visit.createdAt.getTime()) / 1000;
        }
        
        pagesWithDuration.push({
          ...visit.toObject(),
          timeOnPage
        });
      }

      return {
        sessionId,
        website,
        stats: {
          pageViews: visits.length,
          duration: durationInMinutes,
          startTime: firstVisit.createdAt,
          endTime: lastVisit.createdAt,
          referrer: firstVisit.referrer,
          browser: firstVisit.browser,
          os: firstVisit.os,
          device: firstVisit.device,
          country: firstVisit.country,
          city: firstVisit.city
        },
        pages: pagesWithDuration
      };
    } catch (error) {
      throw new Error(`获取会话详情失败: ${error.message}`);
    }
  }
}
